<template>
  <div class="container">
    <!--  系统标题-只有首页，我的显示-->
    <div   v-show="cpNavIsMain && homeTabIndex == 'home'" style="    position: fixed; width: 100%; height: 40px;  top: 0px;  left: 0px; z-index: 999;">
      <img src="../assets/app/top_bg.jpg" class="home-bg" style="height: 40px;width: 100%">
      <div style="     position: absolute;  top: 10px; width: 100%;  color: rgb(255, 255, 255); text-align: center;">
        <img  :src="resources.logoBg()" style="   width: 33px;position: absolute;    border-radius: 5px;"/>
        <span style="    margin-left: 40px;font-size: 13px">
              {{resources.appTitle}}
        </span>
      </div>
    </div>

    <!--  导航-->
    <div  v-show="!cpNavIsMain" style="height: 40px">
      <img src="../assets/app/top_bg.jpg" class="home-bg" style="height: 40px;width: 100%; position: absolute;top:0px;left: 0px;width: 100%">
      <customSpace fullWidth style="padding: 8px 0px 0px 10px">
        <template #content>
          <customButton
            title=""
            @click="toMenu({path:'/home'}, false)"
            style="    width: 25px;border-radius: 50%;background: none;    margin-top: 0px;z-index: 999; border: 0px"
          >
            <customImage :src="iconMain.backHome" :width="20" :height="20" style="background: none"/>
          </customButton>

          <span class="menu-main-title" >{{cpRouteTitle}}</span>
        </template>
      </customSpace>
    </div>

    <!-- 路由-->
    <div  v-if="isRouterAlive">
      <router-view ref="routerView"   class="animated fadeInUp"  :key="$route.fullPath"></router-view>
    </div>

    <t-tabs :value="homeTabIndex"@change="homeTabChange" placement="bottom" class="nav-main" v-show="cpNavIsMain"
            :style="{paddingTop: cpNavIsMain && homeTabIndex == 'home' ? '40px': '0px'}"
    >

      <!--   主页内容-->
      <t-tab-panel value="home" class="panel-main">
        <template #label>
          <div class="box-icon">
            <customImage :src="homeTabIndex == 'home' ? iconMain.home.check :  iconMain.home.unCheck" :width="40" :height="40" class="box-icon-image"/>
          </div>
          <div class="box-text">主页</div>
        </template>
        <t-collapse v-model="moduleExpand" class="animated fadeInUp">
          <!--菜单列表-->
          <t-collapse-panel :header="module.moduleName"  v-for="(module, index) in cpModuleList" :key="module.module"  :value="module.module">
            <template #expandIcon>
              <customImage :src="module.icon" :width="25" :height="25" class="t-button-menu-image"/>
            </template>
            <template #headerRightContent>
              <ChevronRightIcon/>
            </template>
            <div class="t-button-menu-box">
              <t-button  theme="default" class="t-button-menu"
                         v-for="(menu, index2) in module.menuList"  :key="index+'_'+index2"
                         @click="toMenu(menu)"
                         variant="outline"
              >
                <customImage :src="menu.icon" :width="30" :height="30" class="t-button-menu-image"/>
                <div class="btn-text">
                  {{menu.title}}
                </div>
              </t-button>
            </div>

          </t-collapse-panel>
        </t-collapse>
      </t-tab-panel>

      <!--  个人中心-->
      <t-tab-panel value="me"  class="panel-main">
        <template #label>
          <div class="box-icon">
            <customImage :src="homeTabIndex == 'me' ? iconMain.me.check :  iconMain.me.unCheck" :width="40" :height="40" class="box-icon-image"/>
          </div>
          <div class="box-text">个人中心</div>
        </template>
        <div>
          <div >
            <img src="../assets/app/top_bg.jpg" class="home-bg" style="height: 80px;">
            <div style="    position: absolute; top: 20px;  width: 100%; padding: 0px 10px;color: #fff">
              <customImage :src="avatarUrl" :width="40" :height="40" style="display: inline-block;margin-right: 10px;position: absolute;padding: 3px"/>
              <div style="display: inline-block;margin-left: 50px">
                <div>
                  {{username}}
                </div>
                <div style="font-size: 12px">
                  {{userInfoRight}}
                </div>
              </div>
            </div>
          </div>
          <t-space direction="vertical"  style="width: 100%;padding: 0px 3vw;" :size="4"   class="animated fadeInUp">
            <!--
                以下按钮暂时不用
             <t-button block theme="default" variant="base" class="t-button-line" @click="vxHandel('shareUser')"  v-if="false" >
              <ShareIcon slot="icon"  class="t-button_icon_left"/>
              <ChevronRightIcon slot="suffix" />
              分享系统给朋友
            </t-button>

            <t-button block theme="default" variant="base" class="t-button-line" @click="vxHandel('chooseImage')"   v-if="false" >
              <ChevronRightIcon slot="suffix" />
              拍照
            </t-button>

            <t-button block theme="default" variant="base" class="t-button-line" @click="vxHandel('scanQRCode')"  v-if="false" >
              <ChevronRightIcon slot="suffix" />
              微信扫一扫
            </t-button>

            <t-button block theme="default" variant="base" class="t-button-line" @click="vxHandel('openLocation')"  v-if="false"  >
              <ChevronRightIcon slot="suffix" />
              微信内置地图
            </t-button>
            -->

            <!--  微信客户端按钮 开始  -->
            <template  v-if="utils.isVx()">
              <t-button block theme="default" variant="base" class="t-button-line" @click="vxHandel('switchUser')"
                        v-if="cpUserSwitchList.length > 0"
              >
                <UserClearIcon slot="icon"  class="t-button_icon_left"/>
                <ChevronRightIcon slot="suffix" />
                账户切换
              </t-button>

              <t-button block theme="default" variant="base" class="t-button-line" @click="vxHandel('bindUser')"
              >
                <UserAddIcon slot="icon"  class="t-button_icon_left"/>
                <ChevronRightIcon slot="suffix" />
                账户绑定
              </t-button>

              <t-button block theme="default" variant="base" class="t-button-line" @click="vxHandel('setDefaultUser')"
                        v-if="cpUserDefaultList.length > 0"
              >
                <UserAddIcon slot="icon"  class="t-button_icon_left"/>
                <ChevronRightIcon slot="suffix" />
                账号默认登录<span style="    font-size: 11px; padding-left: 10px">{{cpUserDefaultMsg}}</span>
              </t-button>

              <t-button block theme="danger" variant="base" class="t-button-line" @click="logoutvx" >
                <LogoutIcon slot="icon"  class="t-button_icon_left"/>
                <ChevronRightIcon slot="suffix" />
                账户解除微信绑定
              </t-button>
            </template>
            <!--  微信客户端按钮 结束-->

            <t-button block theme="default" variant="base" class="t-button-line"  @click="openLogLocal">
              <ErrorIcon slot="icon"  class="t-button_icon_left"/>
              <ChevronRightIcon slot="suffix" />
              本地操作日志
            </t-button>

            <t-button block theme="default" variant="base" class="t-button-line"  @click="openPwd">
              <Edit1Icon slot="icon"  class="t-button_icon_left"/>
              <ChevronRightIcon slot="suffix" />
              修改密码
            </t-button>

            <t-button block theme="warning" variant="base" class="t-button-line" @click="logout"  v-if="!utils.isVx()">
              <LogoutIcon slot="icon"  class="t-button_icon_left"/>
              <ChevronRightIcon slot="suffix" />
              退出登录
            </t-button>

            <t-button block theme="warning" variant="base" class="t-button-line" @click="vxHandel('close')"   v-if="utils.isVx()">
              <LogoutIcon slot="icon"  class="t-button_icon_left"/>
              <ChevronRightIcon slot="suffix" />
              关闭系统
            </t-button>

            <div  style="font-size: 12px;text-align: center ">
              <strong>版本</strong>
              <span style="padding-left: 10px">{{resources.versionApp}}</span>
            </div>
          </t-space>
        </div>
      </t-tab-panel>
    </t-tabs>

    <!--提示确认框 包含取消按钮-->
    <customDialog ref="customDialogConfirm" theme="warning" cancelBtn="取消" :zIndex="5000"/>

    <!--提示确认框 成功-->
    <customDialog ref="customAlertSuccess" theme="success"/>

    <!--提示确认框 失败-->
    <customDialog ref="customAlertFail" theme="danger"/>
    <!--修改密码-->
    <passwordDrawer ref="customDrawerPsd" />

    <!--全局确认输入框，只有一个文本域输入-->
    <customDrawer :autoHide="false" :title="confirmInputForm.title" ref="confirmInputDrawer"  :widthPx="300" :heightPx="250" @confirm="confirmInputConfirm"  :zIndex="5000">
      <template #content>
        <customForm ref="confirmInputForm" :rules="confirmInputForm.rules"  :data="confirmInputForm" style="margin-top: 30px">
          <template #content>
            <customFormItem
              :label="confirmInputForm.inputLabel"
              name="remark"
              :parent="_self"
              :form="confirmInputForm"
              :type="constCommon.formItemType.textarea.name"
              :config="{minRows: 3, autosize: false, maxRows: 5}"
              fullWidth
              ref="confirmInputFormRemark"
            />
          </template>
        </customForm>
      </template>
    </customDrawer>

    <customDrawer  title="本地异常日志" ref="customDrawerLog" :autoHide="false" p94Only placement="right" :footer="null" attach="body">
      <template #content>
        <customSpace fullWidth style="top: 33px;padding: 5px 0px; position: fixed; top: 33px;  z-index: 999;
    background: #fff;" >
          <template #content>
            <customButton  title="清空日志" theme="primary" size="medium" @click="logClear"/>
          </template>
        </customSpace>

        <DataList
          style="margin-top: 33px"
          ref="dataListLogError"
          :propAutoFetchData="false"
          :propNoCheck="true"
          showFieldMain="time"
          :showFieldList="[{label:'来源',name:'from',span:24,autosize: true,type:'textarea'},{label:'信息',name:'msg',span:24,autosize: true,type:'textarea'}]"
          :propFlagStatic="true"
          :propFlagNoPage="true"
          showValueMain="type"
          showFieldPk="id"
        >
        </DataList>
      </template>
    </customDrawer>

    <customDrawer
      title="切换账号"
      ref="customDrawerUserSelect"
      :widthPx="300"
      :heightPx="291"
      :zIndex="1000"
      :autoHide="false"
      @confirm="userSelectConfirm"
    >
      <template #content>
        <customForm :data="userSelectform" ref="userSelectformRef"  :rules="bindFormRules"  :paddingTop="20">
          <template #content>
            <customFormItem ref="nickname" label="用户名称" name="nickname" :parent="_self" :form="userSelectform"  full-width
                            :type="constCommon.formItemType.selectStatic.name"
                            :config="{options: cpUserSwitchList, label: 'nickname',labelShow: 'nickname', value: 'loginKey'}"
                            @change="nicknameChange"
            />
            <customFormItem label="登录账号" name="loginKey" :parent="_self" :form="userSelectform" full-width disabled
            />
          </template>
        </customForm>
      </template>
    </customDrawer>

    <customDrawer
      title="设置默认登录账户"
      ref="customDrawerUserDefault"
      :widthPx="300"
      :heightPx="291"
      :zIndex="1000"
      :autoHide="false"
      @confirm="userDefaultConfirm"
    >
      <template #content>
        <customForm :data="userDefaultform" ref="userDefaultformRef"  :rules="bindFormRules"  :paddingTop="20">
          <template #content>
            <customFormItem ref="nicknameDefault" label="用户名称" name="nickname" :parent="_self" :form="userDefaultform"  full-width
                            :type="constCommon.formItemType.selectStatic.name"
                            :config="{options: cpUserDefaultList, label: 'nickname',labelShow: 'nickname', value: 'loginKey'}"
                            @change="nicknameDefaultChange"
            />
            <customFormItem label="登录账号" name="loginKey" :parent="_self" :form="userDefaultform" full-width disabled
            />
          </template>
        </customForm>
      </template>
    </customDrawer>

    <customDrawer
      title="绑定新账号"
      ref="customDrawerUserBind"
      :widthPx="300"
      :heightPx="291"
      :zIndex="1000"
      :autoHide="false"
      @confirm="userBindConfirm"
    >
      <template #content>
        <customForm :data="userBindform" ref="userBindformRef"  :rules="bindFormRules" :paddingTop="20">
          <template #content>
            <customFormItem label="账号" name="username" :parent="_self" :form="userBindform" full-width />
            <customFormItem label="密码" name="password" :parent="_self" :form="userBindform" full-width />
            <customFormItem label="默认登录" name="flagDefaultVxLogin" :parent="_self" :form="userBindform"
                            :type="constCommon.formItemType.switch.name"
                            appendMsg="多账号时默认登录账号"
            />
          </template>
        </customForm>
      </template>
    </customDrawer>

    <!--表单打印-->
    <printForm ref="printForm" v-if="isPrintFormShow" @hide="printFormHide"/>

    <pdfView ref="customDrawerPdf"/>
  </div>
</template>

<script>
import { ChevronRightIcon,Edit1Icon,LogoutIcon,ShareIcon,ErrorIcon, UserClearIcon,UserAddIcon } from 'tdesign-icons-vue';

import customImage from '@/components/custom/form/customImage.vue'
import passwordDrawer from '@/components/custom/bus/passwordDrawer'
import printForm from '@/components/app/printForm.vue'
import moduleList from '@/util/const/moduleList.js'
import 'animate.css'
import wx from 'weixin-js-sdk'
import pdfView from '@/components/app/pdfView.vue'

export default {
  help: 'app-主页'
  ,
  data() {
    return {
      isRouterAlive: false,
      homeTabIndex: 'home',
      moduleExpand: [],
      // eslint-disable-next-line global-require
      resources: require('@/settings.js').resources,
      // 输入确认
      confirmInputForm: {
        title: '系统提示',
        autoHide: true,
        inputLabel: '说明',
        comment: '',
        confirmFun: () => {},
        rules: {
          remark: [{ required: true, message: '请输入', trigger: 'blur' }],
        }
      },

      // 图标
      iconMain: {
        backHome:require('@/assets/app/icon/back_home.png'),
        right:require('@/assets/app/icon/right.png'),
        home:  {
          check: require('@/assets/app/icon/home_check.png'),
          unCheck: require('@/assets/app/icon/home_uncheck.png'),
        },
        me:  {
          check: require('@/assets/app/icon/me_check.png'),
          unCheck: require('@/assets/app/icon/me_uncheck.png'),
        }
      },

      userSelectform: {},
      userSelectList: [],
      userBindform: {},
      userDefaultform: {},
      bindFormRules: {
        username: [{ required: true, message: '请输入', trigger: 'blur' }],
        nickname: [{ required: true, message: '请选择', trigger: 'blur' }],
        password: [{ required: true, message: '请输入', trigger: 'blur' }],
      },

      isPrintFormShow: false,

      // 模块列表
      moduleList: []
    }
  },
  computed: {

    // 用户昵称
    username() {
      const username = this.utils.getCurrentUser().nickname
      return username || '获取失败'
    },

    // 右侧信息
    userInfoRight() {
      let deptName = this.utils.getCurrentUser().deptName || null
      let deptType = this.utils.getCurrentUser().deptType || ''
      if (deptName == null || deptType == null) {
        return ''
      }
      let deptTypeName = '平台运营'
      if (this.constCommon.deptType.supplier == deptType) {
        deptTypeName = '供应商'
      }
      if (this.constCommon.deptType.hospital == deptType) {
        deptTypeName = '医院'
      }

      let msg = `机构:${deptName}【${deptTypeName}】`

      return msg
    },

    // 用户头像
    avatarUrl() {
      let deptType = this.utils.getCurrentUser().deptType || ''
      let avatarUrl
      if (deptType == this.constCommon.deptType.hospital) {
        avatarUrl = require('@/assets/app/icon/dept/hp.png')
      } else if (deptType == this.constCommon.deptType.supplier) {
        avatarUrl = require('@/assets/app/icon/dept/sp.png')
      } else {
        avatarUrl = require('@/assets/app/icon/dept/so.png')
      }
      return avatarUrl
    },

    // 菜单模块列表
    cpModuleList() {
      return this.moduleList
    },

    // 是否是主页
    cpNavIsMain() {
      return this.$route.path == '/home'
    },

    // 二级菜单名称
    cpRouteTitle() {
      if (this.$route.meta && this.$route.meta.title) {
        return this.$route.meta.title
      }
      return  ''
    },

    // 默认账号切换可以选择的用户
    cpUserDefaultList() {
      return this.userSelectList.filter(item => !item.flagDefaultVxLogin)
    },

    // 默认账号信息
    cpUserDefaultMsg() {
      let find = this.userSelectList.find(item => item.flagDefaultVxLogin)
      if (find) {
        return  `${find.loginKey}`
      }
      return '未设置'
    },

    // 切换账号切换可以选择的用户
    cpUserSwitchList() {
      let loginKey = this.utils.getCurrentUser().loginKey || ''
      return this.userSelectList.filter(item => loginKey != item.loginKey)
    }
  },
  components: {
    pdfView,
    passwordDrawer,
    customImage,
    ChevronRightIcon,Edit1Icon,LogoutIcon,ShareIcon,ErrorIcon,UserClearIcon,UserAddIcon,printForm
  },
  methods: {
    homeTabChange(newValue) {
      this.homeTabIndex = newValue
      this.utils.vibrate()
    },
    openPwd() {
      this.utils.vibrate()
      this.$refs.customDrawerPsd.show()
    },
    openLogLocal() {
      this.utils.vibrate()
      console.log('this.utils.logList()', this.utils.logList())
      this.$refs.dataListLogError.pushData(this.utils.logList())
      this.$refs.customDrawerLog.show()
    },
    logClear() {
      this.utils.vibrate()
      this.utilMessage.confirm('是否清空本地日志?', () => {
        this.$refs.dataListLogError.pushData([])
        this.utils.logClear()
        this.utilMessage.success('本地日志已清空')
      })
    },
    // 退出登录
    logout() {
      this.utils.vibrate()
      this.utilMessage.confirm('是否退出登录状态', () => {
        utilVue.loadShow(true)
        this.$ajax.delete('/upms/logout').then(resp => {
          utilVue.loadHide()
          sessionStorage.clear()
          let loginForm = JSON.parse(localStorage.getItem('loginForm'))
          if (loginForm){
            loginForm.autologin = false
          }
          if (loginForm && !loginForm.rememberPassword){
            loginForm.password = ''
          }

          localStorage.setItem('loginForm', JSON.stringify(loginForm))
          global.utils.toLogin()
        })
      })
    },
    // 退出登录
    logoutvx() {
      this.utils.vibrate()
      this.utilMessage.confirm('退出并解绑该供应商微信关联，您将无法再收到该供应商系统消息,是否确定', () => {
        utilVue.loadShow(true)
        this.$ajax.delete('/upms/logout?isUnBindVx=1').then(resp => {
          utilVue.loadHide()
          sessionStorage.clear()
          let loginForm = JSON.parse(localStorage.getItem('loginForm'))
          if (loginForm){
            loginForm.autologin = false
          }
          if (loginForm && !loginForm.rememberPassword){
            loginForm.password = ''
          }

          localStorage.setItem('loginForm', JSON.stringify(loginForm))
          global.utils.toLogin()
        })
      })
    },
    // 跳转地址
    _toMenu(menu, query = {}) {
      this.$router.push({
        path: menu.path, query: query
      }, (err) => {
      })
      this.isRouterAlive = true
    },
    // 跳转地址
    toMenu(menu, isDelay = true) {
      this.utils.vibrate()
      if (!isDelay) {
        this._toMenu(menu)
        return
      }
      setTimeout(() => {
        this._toMenu(menu)
      }, 800)
    },
    // 输入确认框确认
    confirmInputConfirm() {
      if (this.confirmInputForm.confirmFun) {
        this.$refs.confirmInputForm.validate().then(result => {
          if (result === true) {
            if (this.confirmInputForm.autoHide) {
              this.$refs.confirmInputDrawer.hide()
            }
            this.confirmInputForm.confirmFun(this.confirmInputForm.remark)
            this.confirmInputForm.remark = ''
          }
        })
      }
    },
    // 输入确认框确认
    bindWxConfig() {
      if (!this.utils.isVx()) {
        return
      }
      this.$ajax.get('/base/userwx/getWxConfig?url='+ location.href).then(resp => {
        if (resp.code == 0) {
          let config = {
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: this.resources.wxAppid, // 必填，公众号的唯一标识
            timestamp: '', // 必填，生成签名的时间戳
            nonceStr: '', // 必填，生成签名的随机串
            signature: '',// 必填，签名
            jsApiList: ["updateAppMessageShareData", "updateTimelineShareData","onMenuShareTimeline","onMenuShareAppMessage", "chooseImage", 'openLocation', 'scanQRCode'] // 必填，需要使用的JS接口列表
          }
          Object.keys(resp.data).forEach(key => {
            config[key] = resp.data[key]
          })
          console.log('微信配置参数', config)
          wx.config(config)
          global.utils.logDebug('微信配置参数',JSON.stringify(config))
        }
      })
    },

    // 的微信操作
    vxHandel(type) {
      this.utils.vibrate()

      switch(type){
        //选择照片
        case 'chooseImage': {
          wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
              var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
              alert('localIds' + localIds)
            }
          })
          break
        }

        //分享系统给朋友
        case 'shareUser': {
          let param = {
            title: this.resources.appTitle + '移动端', // 分享标题
            desc: '请点击访问', // 分享描述
            link: location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            success: function () {
              global.utilMessage.success('分享成功')
            }
          }
          param.title = '标题'
          param.desc = '描述'
          global.utils.logDebug('分享系统给朋友',JSON.stringify(param))

          wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
            try {
              wx.updateAppMessageShareData(param)
            }catch (e) {
              global.utils.logDebug('微信分享--wx.wxerror',e)
            }
          })
          break
        }

        //关闭系统
        case 'close': {
          this.utilMessage.confirm('是否关闭系统', () => {
            wx.closeWindow()
          })
          break
        }

        //微信扫一扫
        case 'scanQRCode': {
          wx.scanQRCode({
            needResult: 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
            scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
            success: function (res) {
              var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
              alert('微信扫一扫' + result)
            }
          })
          break
        }

        //微信内置地图
        case 'openLocation': {
          wx.openLocation({
            latitude: 0, // 纬度，浮点数，范围为90 ~ -90
            longitude: 0, // 经度，浮点数，范围为180 ~ -180。
            name: '', // 位置名
            address: '', // 地址详情说明
            scale: 1, // 地图缩放级别,整型值,范围从1~28。默认为最大
            infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
          })
          break
        }

        //绑定账户
        case 'bindUser': {
          this.$refs.customDrawerUserBind.show()
          break
        }

        //设置默认账户
        case 'setDefaultUser': {
          this.$refs.customDrawerUserDefault.show()
          break
        }

        //切换账号
        case 'switchUser': {
          this.$refs.customDrawerUserSelect.show()
          break
        }
      }
    },

    // 获取用户openid
    getOpenId() {
      // return this.strings.defaultString(localStorage.getItem('vx-openId'),'oB5886yrt4-2aNtUSMxwgjilDL3I')
      return this.strings.defaultString(localStorage.getItem('vx-openId'),'')
    },

    // 切换账号确认
    userSelectConfirm() {
      if (this.strings.isBlank(this.userSelectform.nickname)) {
        this.utilMessage.warning('请选择账号')
        this.$refs.nickname.focus()
        return
      }
      location.href = location.origin + `/login?openId=${this.getOpenId()}&loginKey=${this.userSelectform.loginKey}`
    },

    // 默认登录账户选择后
    nicknameDefaultChange(valueThis, selectItem) {
      Object.keys(selectItem).forEach(key => {
        this.$set(this.userDefaultform, key,selectItem[key])
      })
    },

    // 默认账号选择确认
    userDefaultConfirm() {
      if (this.strings.isBlank(this.userDefaultform.nickname)) {
        this.utilMessage.warning('请选择账号')
        this.$refs.nicknameDefault.focus()
        return
      }
      this.utilVue.loadShow(true)
      this.userDefaultform.openId = this.getOpenId()
      this.$ajax.post(`/base/userwx/setDefaultLogin`, this.userDefaultform).then(resp => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success('操作成功，后续将默认以该账号登录')
          this.$refs.customDrawerUserDefault.hide()
          this.getUserByOpenIdOrLoginKey()
          this.userDefaultform = {}
        }
      })
    },

    // 切换账户选择后
    nicknameChange(valueThis, selectItem) {
      Object.keys(selectItem).forEach(key => {
        this.$set(this.userSelectform, key,selectItem[key])
      })
    },

    // 可选择用户列表
    getUserByOpenIdOrLoginKey() {
      let openId = this.getOpenId()
      if (this.strings.isBlank(openId)) {
        return
      }
      this.$ajax.get(`/base/userwx/getUserByOpenIdOrLoginKey?openId=${openId}`).then(response => {
        if (response.code == 0) {
          this.userSelectList = response.data || []
        }
      })
    },

    // 绑定账号
    userBindConfirm() {
      this.$refs.userBindformRef.validate().then((result) => {
        if (result && result == true) {
          this.utilVue.loadShow(true)
          this.userBindform.openId =  this.getOpenId()
          this.$ajax
            .post('/base/userwx/bind', this.userBindform)
            .then((resp) => {
              this.utilVue.loadHide()
              if (resp.code == 0) {
                this.utilMessage.success('绑定成功')
                this.$refs.customDrawerUserBind.hide()
                this.userBindform = {}
                this.getUserByOpenIdOrLoginKey()
              }
            })
        }
      })
    },

    // 初始化菜单
    initMenu() {
      let deptType = this.utils.getCurrentUser().deptType || ''
      let moduleListTmp = []
      let menuList
      let moduleTmp
      Object.keys(moduleList).forEach(moduleKey => {
        moduleTmp = moduleList[moduleKey]
        menuList = moduleTmp.menuList
        // 菜单过滤
        if (!this.utils.getCurrentUser().isAdmin) {
          menuList = menuList.filter(item => !item.deptTypeFilter || item.deptTypeFilter().includes(deptType))
        }
        moduleTmp.menuList = menuList

        moduleListTmp.push(moduleTmp)
      })

      // 模块过滤
      moduleListTmp = moduleListTmp.filter(item => !item.deptTypeFilter || item.deptTypeFilter().includes(deptType))
      if (!this.utils.getCurrentUser().isAdmin){
        moduleListTmp = moduleListTmp.filter(item => !item.isAdmin)
      }
      this.moduleList = moduleListTmp

      // 展开所有菜单
      this.moduleExpand = this.cpModuleList.map(item => {
        return item.module
      })
      if (!this.cpNavIsMain) {
        this.$router.push({
          path: this.$route.path,
        }, (err) => {
          console.error(err)
        })
        this.isRouterAlive = true
      }
    },

    // 初始化数据
    initData() {
      this.initMenu()
      this.bindWxConfig()
      this.getUserByOpenIdOrLoginKey()

      // 医院列表
      this.$ajax.get('/base/hospitals/listUser')
      .then((resp) => {
        if (resp.code == 0) {
          this.$store.dispatch('setHospitalList', resp.data)
        }
      })

      // 医院列表
      this.$ajax.get('/base/suppliers/listCommon')
      .then((resp) => {
        if (resp.code == 0) {
          this.$store.dispatch('setSpList', resp.data)
        }
      })

      // 数据字典
      this.$ajax.get('/upms/dict_datas/list')
      .then((resp) => {
        if (resp.code == 0) {
          this.$store.dispatch('setDictDataList', resp.data)
        }
      })

      // 资质类型
      this.$ajax.get('/cert/certificates/listCommon')
      .then((resp) => {
        if (resp.code == 0) {
          this.$store.dispatch('setCertTypeList', resp.data)
        }
      })
    },

    printFormShow( param) {
      this.isPrintFormShow = true
      setTimeout(() => {
        this.$refs.printForm.show(param)
      }, 500)
    },

    printFormHide() {
      this.isPrintFormShow = false
    },

    // 监听返回，用户如果不操作只能触发一次
    onBackCloseWindow () {
      var state = {
        date: Date.now()
      };
      window.history.pushState(state, 'csb')
      let that = this
      window.addEventListener('popstate', () => {
        if (this.cpNavIsMain && !this.isRouterAlive) {
          that.utilMessage.confirm('是否退出系统?', () => {
            wx.closeWindow()
          })
        }
      })
    }
  },
  mounted() {
    this.initData()
    if (this.utils.isVx()) {
      this.onBackCloseWindow()
    }
  },
}
</script>

<style lang="scss">

.nav-main{
  .t-tab-panel{
  }
  .t-collapse-panel__content{
    background: #fff;
  }
  .t-tabs__content{
    max-height: calc(100vh - 110px);
    overflow-y: auto;
    overflow-x: hidden;
    padding-bottom: 100px;
  }
  .t-tabs__nav-scroll{
    width: 100%;
    display: block;
  }
  .t-tabs__nav-item-text-wrapper{
    display: block;
    .box-icon{
      line-height: 100%;
      text-align: center;
      .t-icon{
        font-size: 21px;
      }
      .box-icon-image{
        width: 22px !important;
        height: 22px !important;
        display: inline-block !important;
      }
    }
    .box-text{
      line-height: 20px;
      font-size: 11px;
    }
  }
  .t-tabs__header{
    position: fixed;
    bottom: 0px;
    width: 100%;
    left: 0px;
    padding: 0px 10px 0px 0px;
    background: #fff;
    z-index: 999;
  }

  .t-tabs__nav-item{
    width: 50%;

  }

  .t-tabs__nav-item-wrapper{
    display: block;
    width: 100%;
    text-align: center;
    padding-top: 7px;
  }
  .t-tabs__nav-item-wrapper,.t-tabs__nav-item{
    height: 50px !important;
    line-height: 50px !important;
  }

  .t-is-active .t-icon{
    color: #0052d9;
  }
}

.t-button-line{
  height: 40px !important;
  .t-button_icon_left{
    position: absolute !important;
    left: 3px !important;
  }
  .t-button__text{
    position: absolute !important;
    left: 20px !important;
  }
  .t-button__suffix{
    position: absolute;
    right: 3px;
  }
}

.t-button-menu-box{
  .t-button-menu{
    width: 80px;
    height: 80px !important;
    margin-right: 10px !important;
    margin-bottom: 10px;
    .t-button_icon_left{
      position: absolute !important;
      width: 30px !important;
      height: 30px !important;
      top: 5px !important;
      left: 13px !important;
    }
    .btn-text{
      margin-top: 40px;
      font-size: 12px;
    }
    .t-button__suffix{
    }
    .t-button-menu-image{
      left: 24%;
      position: absolute;
      top: 5px;
    }
  }
}


@import "../styles/color.scss";
.box-title{
  position: relative;
  width: 100%;
  font-size: 16px;
  border-bottom: 1px solid $border-color;
  padding: 5px 10px;
  background: #f5f5f5;
  transition: all 1s;
  -webkit-transition: all 1s;
  cursor: pointer;

  &:after{
    position: absolute;
    content: '';
    left: 0;
    top:20%;
    width: 3px;
    height: 60%;
    background-color: $secondary-light-color;
  }

  /*二级标题*/
  .box-title2 {
    font-size: 13px;
    margin-left: 13px;
    color: #ef760fd4;
  }
}

.menu-main-title{
  position: absolute;
  top: 12px;
  text-align: center;
  width: 100%;
  left: 0px;
  font-size: 13px;
  font-weight: 500;
  color: #fff;
  letter-spacing: 2px;
}
.home-bg{
  width: 100%;
}
</style>

